<template>
    <div class="category-detail-page">
        <el-card shadow="never">
            <el-form
                :model="form"
                label-position="right"
                label-suffix=":"
                label-width="100px"
                ref="form"
                :rules="rules">
                <el-form-item label="名称" prop="name">
                    <el-input
                        v-model="form.name"
                        placeholder="请输入员工名称"
                        class="input-width"
                    ></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input
                        v-model="form.email"
                        placeholder="请输入邮箱"
                        class="input-width"
                    ></el-input>
                </el-form-item>
                <el-form-item label="账号配额" v-if="! this.id" prop="application_id">
                    <el-select
                        v-model="form.application_id"
                        clearable>
                        <el-option
                            v-for="item in applicationOptions"
                            :key="item.id"
                            :label="`激活1个账号配额。（激活后还有${item.count - item.used_count - 1} 个，
                            每个可用${item.duration}天的账号配额 ）`"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号" :required="!id">
                    <el-input
                        v-model="form.phone"
                        placeholder="请输入手机号"
                        class="input-width"
                    ></el-input>
                </el-form-item>
                <el-form-item label="头像" prop="avatar">
                    <file-upload :type="1" :multiple="false" v-model="form.avatar">
                        <img
                            v-if="form.avatar"
                            :src="form.avatar"
                            class="uploader-icon picture image-uploader"
                        />
                        <i v-else class="el-icon-plus uploader-icon picture image-uploader"></i>
                    </file-upload>
                </el-form-item>
                <el-form-item label="职位">
                    <el-select
                        v-model="form.position_id"
                        clearable>
                        <el-option
                            v-for="item in positionOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="团队">
                    <el-select
                        v-model="form.team_id"
                        clearable>
                        <el-option
                            v-for="item in teamOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item> -->
            </el-form>
            <div class="text-center">
                <el-button :loading="posting" type="primary" @click="onSave">保 存</el-button>
                <el-button  @click="$router.back()">返 回</el-button>
            </div>
        </el-card>
    </div>
</template>

<script>
import FileUpload from '../../components/base/FileUpload';

export default {
    components: {
        FileUpload,
    },
    data() {
        return {
            posting: false,
            form: {
                name: '',
                email: '',
                phone: '',
                avatar: '',
                team_id: '',
                role_id: '',
                position_id: '',
                application_id: '',
            },
            id: this.$route.params.id,
            positionOptions: [],
            roleOptions: [],
            teamOptions: [],
            applicationOptions: [],
            rules: {
                name: [
                    { required: true, message: '员工名称不能为空', trigger: 'blur' },
                ],
                email: [
                    { required: true, message: '邮箱账号不能为空', trigger: 'blur' },
                ],
                phone: [
                    { required: true, message: '手机号不能为空', trigger: 'blur' },
                ],
                application_id: [
                    { required: true, message: '请选择一个配额给员工账号', trigger: 'blur' },
                ],
            },
        };
    },
    methods: {
        onSave() {
            if (!this.id && !this.form.phone) return $ele.$message.warning('请输入手机号');

            this.$refs.form.validate((valid) => {
                if (!valid) return;
                this.posting = true;
                this.form.email = this.form.email.trim();
                if (this.id) {
                    API.put(`user/${this.id}`, this.form).then(() => {
                        this.$router.push({name: 'UserManage'});
                    }).catch(err => {
                        $ele.$message.error(err.message);
                    }).finally(() => this.posting = false);
                } else {
                    API.post('user', this.form).then((res) => {
                        this.posting = false;
                        $ele.$confirm(`新建员工账号成功，账号的登陆密码是${res.password}`, '提示', {
                            confirmButtonText: '确定',
                            type: 'warning',
                        }).then(() => {
                            this.$router.push({name: 'UserManage'});
                        }).catch(() => {
                            this.$router.push({name: 'UserManage'});
                        });
                    }).catch(err => {
                        $ele.$message.error(err.message);
                    }).finally(() => this.posting = false);
                }
            });
        },
        fetchData() {
            if (this.id) {
                API.get(`user/${this.id}`).then((res) => {
                    for (const i of Object.keys(this.form)) {
                        if (res[i]) this.form[i] = res[i];
                    }
                });
            }
        },
        fetchPositionData() {
            API.get('position/list').then((res) => {
                this.positionOptions = res;
            });
        },
        fetchRoleData() {
            const userRoleType = 4;
            API.get('role/list', {
                params: {
                    type: userRoleType,
                },
            }).then((res) => {
                this.roleOptions = res;
            });
        },
        fetchTeamData() {
            const teamRoleType = 3;
            API.get('role/list', {
                params: {
                    type: teamRoleType,
                },
            }).then((res) => {
                this.teamOptions = res;
            });
        },
        fetchApplicationData() {
            API.get('account/application/list').then((res) => {
                this.applicationOptions = res.filter(option => option.count > option.used_count);
            });
        },
    },
    mounted() {
        this.fetchData();
        this.fetchPositionData();
        this.fetchRoleData();
        this.fetchTeamData();
        this.fetchApplicationData();
    },
};
</script>

<style lang="scss">
.category-detail-page {
    .input-width {
        width: 300px;
    }
    .picture {
        width: 200px;
        height: 200px;
        line-height: 200px;
    }
    .uploader-icon {
        font-size: 20px;
        color: #8c939d;
        text-align: center;
    }
    .image-uploader {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
}
</style>
